package xyz.penghaonan.p2plib.helper.p2phelper;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageManager;
import android.net.wifi.WpsInfo;
import android.net.wifi.p2p.WifiP2pConfig;
import android.net.wifi.p2p.WifiP2pDevice;
import android.net.wifi.p2p.WifiP2pDeviceList;
import android.net.wifi.p2p.WifiP2pGroup;
import android.net.wifi.p2p.WifiP2pInfo;
import android.net.wifi.p2p.WifiP2pManager;
import android.os.Looper;
import android.text.TextUtils;

import com.penghaonan.appframework.AppDelegate;
import com.penghaonan.appframework.utils.WeakObservableList;

import java.util.ArrayList;
import java.util.Collection;

import xyz.penghaonan.p2plib.utils.P2PActionListener;

/**
 * author: duke
 * version: 1.0
 * dateTime: 2019-05-20 18:26
 * description: https://developer.android.google.cn/guide/topics/connectivity/wifip2p
 * Android 4.0 设备
 */
public class WifiP2PHelper {

    private WifiP2pManager mManager;
    private WifiP2pManager.Channel mChannel;
    private WifiP2PBroadCastReceiver mReceiver;

    private Context context;
    private static final WeakObservableList<WifiP2PListener> listenerList = new WeakObservableList<>();

    public WifiP2PHelper() {
        context = AppDelegate.getApp();

        mManager = (WifiP2pManager) context.getSystemService(Context.WIFI_P2P_SERVICE);
        // 将此应用注册到 WLAN P2P 框架
        mChannel = mManager.initialize(context, Looper.getMainLooper(), null);
        mReceiver = new WifiP2PBroadCastReceiver(this, mManager, mChannel);
        mReceiver.setListenerList(listenerList);
    }

    public void addListener(WifiP2PListener listener) {
        listenerList.addListener(listener);
    }

    public void removeListener(WifiP2PListener listener) {
        listenerList.removeListener(listener);
    }

    public boolean isSupportWifiP2P() {
        return context != null
                && context.getPackageManager() != null
                && context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_WIFI_DIRECT);
    }

    @SuppressLint("MissingPermission")
    public void createGroup(P2PActionListener listener) {
        mManager.createGroup(mChannel, new ActionListenerWrapper(listener) {
            @Override
            public void onSuccess() {
                super.onSuccess();
                listenerList.iterate(new WeakObservableList.OnIterator<WifiP2PListener>() {
                    @Override
                    protected boolean onIterator(WifiP2PListener item) {
                        item.onCreateGroup(true);
                        return false;
                    }
                });
            }

            @Override
            public void onFailure(int reason) {
                super.onFailure(reason);
                listenerList.iterate(new WeakObservableList.OnIterator<WifiP2PListener>() {
                    @Override
                    protected boolean onIterator(WifiP2PListener item) {
                        item.onCreateGroup(false);
                        return false;
                    }
                });
            }
        });
    }

    public void removeGroup(P2PActionListener listener) {
        mManager.removeGroup(mChannel, new ActionListenerWrapper(listener) {
            @Override
            public void onSuccess() {
                listenerList.iterate(new WeakObservableList.OnIterator<WifiP2PListener>() {
                    @Override
                    protected boolean onIterator(WifiP2PListener item) {
                        item.onRemoveGroup(true);
                        return false;
                    }
                });
            }

            @Override
            public void onFailure(int reason) {
                listenerList.iterate(new WeakObservableList.OnIterator<WifiP2PListener>() {
                    @Override
                    protected boolean onIterator(WifiP2PListener item) {
                        item.onRemoveGroup(false);
                        return false;
                    }
                });
            }
        });
    }

    @SuppressLint("MissingPermission")
    public void connect(WifiP2pDevice wifiP2pDevice, P2PActionListener listener) {
        if (wifiP2pDevice == null || TextUtils.isEmpty(wifiP2pDevice.deviceAddress)) {
            return;
        }
        WifiP2pConfig config = new WifiP2pConfig();
        config.deviceAddress = wifiP2pDevice.deviceAddress;
        config.wps.setup = WpsInfo.PBC;
        mManager.connect(mChannel, config, new ActionListenerWrapper(listener) {
            @Override
            public void onSuccess() {
                listenerList.iterate(new WeakObservableList.OnIterator<WifiP2PListener>() {
                    @Override
                    protected boolean onIterator(WifiP2PListener item) {
                        item.onConnectCallChanged(true);
                        return false;
                    }
                });
            }

            @Override
            public void onFailure(int reason) {
                listenerList.iterate(new WeakObservableList.OnIterator<WifiP2PListener>() {
                    @Override
                    protected boolean onIterator(WifiP2PListener item) {
                        item.onConnectCallChanged(false);
                        return false;
                    }
                });
            }
        });
    }

    /**
     * 取消任何正在进行的对等群组协商
     */
    public void cancelConnect() {
        mManager.cancelConnect(mChannel, new WifiP2pManager.ActionListener() {
            @Override
            public void onSuccess() {
                listenerList.iterate(new WeakObservableList.OnIterator<WifiP2PListener>() {
                    @Override
                    protected boolean onIterator(WifiP2PListener item) {
                        item.onDisConnectCallChanged(true);
                        return false;
                    }
                });
            }

            @Override
            public void onFailure(int reason) {
                listenerList.iterate(new WeakObservableList.OnIterator<WifiP2PListener>() {
                    @Override
                    protected boolean onIterator(WifiP2PListener item) {
                        item.onDisConnectCallChanged(false);
                        return false;
                    }
                });
            }
        });
    }

    @SuppressLint("MissingPermission")
    public void discover(P2PActionListener listener) {
        mManager.discoverPeers(mChannel, new ActionListenerWrapper(listener) {
            @Override
            public void onSuccess() {
                listenerList.iterate(new WeakObservableList.OnIterator<WifiP2PListener>() {
                    @Override
                    protected boolean onIterator(WifiP2PListener item) {
                        item.onDiscoverPeers(true);
                        return false;
                    }
                });
            }

            @Override
            public void onFailure(int reason) {
                listenerList.iterate(new WeakObservableList.OnIterator<WifiP2PListener>() {
                    @Override
                    protected boolean onIterator(WifiP2PListener item) {
                        item.onDiscoverPeers(false);
                        return false;
                    }
                });
            }
        });
    }

    /**
     * 请求最新的配对数据列表
     */
    @SuppressLint("MissingPermission")
    public void requestPeers() {
        mManager.requestPeers(mChannel, new WifiP2pManager.PeerListListener() {
            @Override
            public void onPeersAvailable(WifiP2pDeviceList peers) {
                final Collection<WifiP2pDevice> collection;
                if (peers != null) {
                    collection = peers.getDeviceList();
                } else {
                    collection = new ArrayList<>();
                }
                listenerList.iterate(new WeakObservableList.OnIterator<WifiP2PListener>() {
                    @Override
                    protected boolean onIterator(WifiP2PListener item) {
                        item.onPeersAvailable(collection);
                        return false;
                    }
                });
            }
        });
    }

    /**
     * 请求设备连接信息
     */
    public void requestConnectInfo() {
        mManager.requestConnectionInfo(mChannel, new WifiP2pManager.ConnectionInfoListener() {

            @Override
            public void onConnectionInfoAvailable(final WifiP2pInfo info) {
                listenerList.iterate(new WeakObservableList.OnIterator<WifiP2PListener>() {
                    @Override
                    protected boolean onIterator(WifiP2PListener item) {
                        item.onConnectionInfoAvailable(info);
                        return false;
                    }
                });
            }
        });
    }

    /**
     * 请求设备连接信息
     */
    @SuppressLint("MissingPermission")
    public void requestGroupInfo() {
        mManager.requestGroupInfo(mChannel, new WifiP2pManager.GroupInfoListener() {

            @Override
            public void onGroupInfoAvailable(final WifiP2pGroup group) {
                listenerList.iterate(new WeakObservableList.OnIterator<WifiP2PListener>() {
                    @Override
                    protected boolean onIterator(WifiP2PListener item) {
                        item.onGroupInfoAvailable(group);
                        return false;
                    }
                });
            }
        });
    }

    public String getDeviceStatus(int deviceStatus) {
        switch (deviceStatus) {
            case WifiP2pDevice.AVAILABLE:
                return "可用的";
            case WifiP2pDevice.INVITED:
                return "邀请中";
            case WifiP2pDevice.CONNECTED:
                return "已连接";
            case WifiP2pDevice.FAILED:
                return "失败的";
            case WifiP2pDevice.UNAVAILABLE:
                return "不可用的";
            default:
                return "未知";
        }
    }

    public void registerReceiver() {
        if (mReceiver != null) {
            mReceiver.registerReceiver(context);
        }
    }

    public void unRegisterReceiver() {
        if (mReceiver != null) {
            mReceiver.unRegisterReceiver(context);
        }
    }

    private static class ActionListenerWrapper implements WifiP2pManager.ActionListener {

        private final WifiP2pManager.ActionListener listener;

        public ActionListenerWrapper(WifiP2pManager.ActionListener listener) {
            this.listener = listener;
        }

        @Override
        public void onSuccess() {
            if (listener != null) {
                listener.onSuccess();
            }
        }

        @Override
        public void onFailure(int reason) {
            if (listener != null) {
                listener.onFailure(reason);
            }
        }
    }
}
